import {
  api,
  storage,
  util
} from "../util";
import authorize from './authorize.js'
import {wholesaleSettings} from "./gloab.js";
import {detail} from '../modules/mall';
import { alert, deepClone, getLengthAfterDot, isEmpty } from "../newUtil";
const app = getApp();


/**优惠劵 */
var coupon = {
  //优惠券详情
  getCouponsDetail(couponsId, callback) {
    var entity = authorize.getEntity();
    var param = {
      CouponsId: couponsId,
      isLogin: authorize.isLogin("store") ? "1" : "0",
      FKWay: app.dns.fkWay,
      ReceiveId: entity.fkId,
      ReceiveFlag: entity.fkFlag,
      ProprietorId: app.dns.proprietorId,
      Token: entity.manager.Token
    };
    util.post("market.coupons.details", param, function (res) {

      if (callback != undefined && typeof (callback) == "function") {
        callback(res.data.Content);
      }
    });
  },
  praseTerminalName: function(terminal) {
    switch (terminal.toString()) {
      case '0':
        return "不限终端";
      case '1':
        return "限PC端";
      case '2':
        return "限移动端";
      default:
        return '';
    }
  },
  praseCouponStatus: function (item, className = "got", useDesc ="立即使用") {
    var c = "", btnDesc = "";
    if (item.PullCount>0){
      c = className;
    }
    if (item.DrawCount >= item.Quantity) {
      //已领完      
      btnDesc = "已领完";
    }
    else if (item.PullCount == 0 || item.IsLogin == '0') {
      //立即领取
      btnDesc = "立即领取";
    }
    else if (item.EveryDayNum == 0) {
      if (item.PullCount < item.RestrictNum || item.RestrictNum == 0) {
        //继续领取
        btnDesc = "继续领取";
      }
      else {
        //立即使用
        btnDesc = useDesc;
      }
    }
    else {
      //判断上次领取时间是否是当前时间
      if (item.IsAgainPull == 1) {
        //立即领取
        btnDesc = "立即领取";
      }
      else {
        //立即使用
        btnDesc = useDesc;
      }
    }
    item.ClassName = c;
    if (item.GrantType == 5) {
      // 积分兑换优惠券，替换显示文字
      btnDesc = btnDesc.replace(/领取/img, '兑换')
      btnDesc = btnDesc.replace(/领/img, '兑')
    }
    item.BtnDesc = btnDesc;
    return item;
  },
  /**
   * [onlineReceivedCoupon 领取优惠券]
   * @param  {[type]}   id   [优惠券id]
   * @param  {[type]}   fromFkId   [发放者]
   * @param  {[function]}   callback   [回调函数]
   * @param {Number} type 优惠券类型，5：积分兑换
   */
  onlineReceivedCoupon: function(id, fromFkId, callback, type) {
    var entity = authorize.getEntity();

    var param = {
      CouponId: id,
      FromFkId: fromFkId,
      FKWay: app.dns.fkWay,
      Token: entity.manager.Token,
      ReceiveId: entity.fkId,
      ReceiveFlag: entity.fkFlag,
      ProprietorId: app.dns.proprietorId
    };
    util.post("market.coupon.receive", param, function(res) {
      res = res.data;
      if (res.Success) {
        //回调
        let message = '领取成功'
        if (type == 5) {
          message = '兑换成功'
        }
        util.success(message, function(){
          if (callback != undefined && typeof (callback) == "function") {
            callback();
          }
        });

       
      } else {
        util.alert("操作失败:" + res.Message);

      }

    }, "3.0",null,false);
  },
  /**加载商品优惠劵 */
  loadProductCoupons(productId, callback) {
    var entity = authorize.getEntity() || authorize.getDefault();
    var param = {
      Proprietor: app.dns.proprietor,
      ProprietorId: app.dns.proprietorId,
      FKWay: app.dns.fkWay,
      ReceiveFlag: entity.fkFlag,
      ReceiveId: entity.fkId,
      levelId: entity.role.LevelId,
      productId: productId,
      isLogin: authorize.isLogin("store") ? "1" : "0",
      PageIndex: 1,
      PageSize: 20,
      formFKId: app.dns.proprietorId,
      fkFlag: entity.fkFlag,
      fkId: entity.fkId,
      Token: entity.manager.Token
    };
    util.post("market.product.coupons", param, function(res) {
      res = res.data;
      if (res.Success) {
        if (callback != undefined && typeof(callback) == "function") {
          callback(res.Content);
        }
      }
    });
  },
  /**已领取的优惠券列表 */
  loadReceviedCoupons(data, callback) {
    var entity = authorize.getEntity();
    var param = {
      Proprietor: app.dns.proprietor,
      ProprietorId: app.dns.proprietorId,
      FKWay: app.dns.fkWay,
      ReceiveFlag: entity.fkFlag,
      ReceiveId: entity.fkId,
      Used: data.Used,
      PageIndex: data.PageIndex,
      PageSize: data.PageSize,
      Token: entity.manager.Token
    };
    util.post("market.coupon.my.list", param, function(res) {
      if (callback != undefined && typeof(callback) == "function") {
        callback(res.data.Content);
      }
    });
  },
  /**获取优惠劵种类的数量 */
  loadCouponsCount(callback) {
    var entity = authorize.getEntity();
    var param = {
      Proprietor: app.dns.proprietor,
      ProprietorId: app.dns.proprietorId,
      ReceiveFlag: entity.fkFlag,
      ReceiveId: entity.fkId
    };
    util.post("market.coupon.received.count", param, function(res) {
      if (callback != undefined && typeof(callback) == "function") {
        callback(res.data.Content);
      }
    });
  },
  /**在线领取优惠劵列表 */
  loadOnlineCouponsList(data, callback) {
    var entity = authorize.getEntity() || authorize.getDefault();
    var param = {
      Proprietor: app.dns.proprietor,
      ProprietorId: app.dns.proprietorId,
      FKWay: app.dns.fkWay,
      ReceiveFlag: entity.fkFlag,
      ReceiveId: entity.fkId,
      UserId:entity.fkId,
      isLogin: authorize.isLogin("store") ? "1" : "0",
      PageIndex: data.PageIndex,
      PageSize: data.PageSize,
      formFKId: app.dns.proprietorId,
      ProductId: data.ProductId
    };
    util.post("market.coupon.receive.list", param, function(res) {

      if (callback != undefined && typeof(callback) == "function") {
        callback(res.data.Content);
      }
    });
  },
  /**
   * 获得优惠券说明
   */
  getCouponInstructions(data, callback) {
    var entity = authorize.getEntity();
    var param = {
      fromFkId: entity.fkFlag,
      ruleId: data.ruleId,
      isApply: data.isApply
    };
    var config = wholesaleSettings.getConfig();
    var Currency = data.Currency;
    util.post("market.coupon.instructions", param, function(res) {
      res = res.data;
      if (res.Success) {
        var d = res.Content || {};
        var coupon = d.entity || {};
        var products = d.products || [];
        var brands = d.brands || [];
        var categorys = d.categorys || [];
        var discountMode = coupon.DiscountMode || 0;
        var terminal = coupon.Terminal || 0;
        let goodsRequired = d.goodsrequired || []
        var instruction = {
          name: coupon.Name || "",
          discountValue: (discountMode == 1 || discountMode == 4) ? Currency + (coupon.DiscountValue || 0) : (util.formatFloat(coupon.DiscountValue * 10 ,config.priceDigits) + "折"),
          discountText: "满" + (coupon.MinimumValue || 0) + (discountMode == 1 || discountMode == 2 ? "元" : "个") + "可用",
          terminals: terminal == 1 ? "限PC端" : (terminal == 2 ? "限移动端" : "不限终端"),
          brands: brands,
          categorys: categorys,
          products: products,
        };
        if (brands.length > 0) {
          instruction.brandText = "";
          for (var i = 0, len = brands.length; i < len; i++) {
            var brand = brands[i]
            instruction.brandText = (brand.BrandName || "")
            if (i < len - 1) {
              instruction.brandText += '、'
            }
          }
        }
        if (categorys.length > 0) {
          instruction.categoryText = "";
          for (var i = 0, len = categorys.length; i < len; i++) {
            var category = categorys[i];
            instruction.categoryText += (category.CategoryName || "") + "\n";
          }
        }

        if (products.length > 0) {
          instruction.productText = "";
          for (var i = 0, len = products.length; i < len; i++) {
            var product = products[i];
            instruction.productText += (product.GoodsName || "") + "\n";
          }
        }
        // 必买商品
        if (goodsRequired.length > 0) {
          instruction.goodsRequiredText = ''
          for (let i = 0; i < goodsRequired.length; i++) {
            let item = goodsRequired[i]
            instruction.goodsRequiredText += `${item.ProductName || ''} x ${item.MinBuyNum}${item.UnitName || ''}\n`
          }
        }
        var describes = [];
        describes.push({
          name: "优惠券名称",
          value: instruction.name
        });
        describes.push({
          name: "优惠券面额",
          value: instruction.discountValue
        });
        describes.push({
          name: "使用限额",
          value: instruction.discountText
        });
        describes.push({
          name: "适用终端",
          value: instruction.terminals
        });
        if (instruction.brandText)
          describes.push({
            name: "适用品牌",
            value: instruction.brandText
          });
        if (instruction.categoryText)
          describes.push({
            name: "适用目录",
            value: instruction.categoryText
          });
        if (instruction.productText)
          describes.push({
            name: "适用商品",
            value: instruction.productText
          });
        if (instruction.goodsRequiredText) {
          describes.push({
            name: "必买商品",
            value: instruction.goodsRequiredText
          });
        }
        // 优惠券说明显示使用时间
        if (coupon.StartTime) {
          describes.push({
            name: '使用时间',
            value: `${coupon.StartTime} - ${coupon.EndTime}`
          });
        }
        let name = []
        let PayType = ['货到付款', '在线支付', '授信支付', '转账汇款', '线下付款']
        let Logistics = ['物流快递', '到店自提', '商家配送']
        let Scene = ['客户自下单可用', '代下单可用']
        let UseScene = coupon.UseScene || ''
        // 优惠券说明显示使用场景
        if (!isEmpty(UseScene)) {
          Scene.unshift('')
          let arr = UseScene.split(',')
          arr = Array.from(new Set(arr))
          arr.map((i) => {
            i = parseInt(i)
            name.push(Scene[i])
          })
        } else {
          name = Scene
        }
        if (name.length > 0) {
          describes.push({
            name: '使用场景',
            value: name.join(',')
          })
        }
        let PayTypeId = coupon.PayTypeId || ''
        name = []
        // 优惠券说明显示支付方式
        if (!isEmpty(PayTypeId)) {
          PayType.unshift('')
          let arr = PayTypeId.split(',')
          arr = Array.from(new Set(arr))
          arr.map((i) => {
            i = parseInt(i)
            name.push(PayType[i])
          })
        } else {
          name = PayType
        }
        if (name.length > 0) {
          describes.push({
            name: '支付方式',
            value: name.join(',')
          })
        }
        let LogisticsTypeId = coupon.LogisticsTypeId || ''
        name = []
        // 优惠券说明显示物流方式
        if (!isEmpty(LogisticsTypeId)) {
          let arr = LogisticsTypeId.split(',')
          arr = Array.from(new Set(arr))
          arr.map((i) => {
            i = parseInt(i)
            name.push(Logistics[i])
          })
        } else {
          name = Logistics
        }
        if (name.length > 0) {
          describes.push({
            name: '物流方式',
            value: name.join(',')
          })
        }
        if (callback != undefined && typeof(callback) == "function") {
          callback({
            describes: describes,
            instruction: instruction
          });
        }

      }

    });
  },
  /**
   * 获得大礼包
   */
  getCouponGift(data, callback) {
    var entity = authorize.getEntity()|| authorize.getDefault()
    var param = {
      Proprietor: app.dns.proprietor,
      ProprietorId: app.dns.proprietorId,
      UserId: entity.fkId,
      FKId: app.dns.proprietorId,
      FKFlag: app.dns.proprietor
    };
    util.post("market.coupon.getcoupongift", param, function (res) {
      res = res.data;
      if (res.Success) {
        if (callback != undefined && typeof (callback) == "function") {
          callback(res.Content);
        }
      }
    },"3.0",null,false)
  },
  /**
   * 领取大礼包
   */
  receiveCouponGift(data, callback) {
    var entity = authorize.getEntity();
    var param = {
      Proprietor: app.dns.proprietor,
      ProprietorId: app.dns.proprietorId,
      UserId: entity.fkId,
      FKId: app.dns.proprietorId,
      FKFlag: app.dns.proprietor,
      CouponGift: data.couponGiftId,
      Type:data.type,
      ReceiveFlag: entity.fkFlag
    };
    util.post("market.coupon.receivecoupongift", param, function (res) {
      res = res.data;
      if (callback != undefined && typeof (callback) == "function") {
        callback(res);
      }
    
    },"3.0",null,false)
  },
  /**
   *  更新展现量\点击量
   */
  updateScanNum(data, callback) {
    var entity = authorize.getEntity();
    var param = {
      Proprietor: app.dns.proprietor,
      ProprietorId: app.dns.proprietorId,
      Type:data.type,
      CouponGift: data.couponGiftId,
      Count: data.count
    };
    util.post("market.coupon.updcount", param, function (res) {
      res = res.data;
      if (callback != undefined && typeof (callback) == "function") {
        callback(res);
      }

    }, "3.0", null, false)
  },
}
var group = {
  /**加载拼团预售商品列表 */
  loadGroupProductList(data, callback) {
    var entity = authorize.getEntity();
    var param = {
      FKFlag: app.dns.proprietor,
      FKId: app.dns.proprietorId,
      ProprietorId: app.dns.proprietorId,
      ZoneId: app.dns.proprietorId,
      FKWay: app.dns.fkWay,
      UserId:entity.fkId,
      PageIndex: data.PageIndex,
      PageSize: data.PageSize,
      keywords: data.keywords,
      sortField: data.sortField,
      sortDirect: data.sortDirect,
      GroupStatus: data.GroupStatus,
      Flag: data.Flag,
      Status: 1,
      IsShow: 1,
      Shelved: 1
    };
    util.post("market.groupbuy.list", param, function(res) {
      res = res.data;
      if (res.Success) {
        group.set_differ_time(res.Content.Data, data.GroupStatus);
        if (callback != undefined && typeof(callback) == "function") {
          callback(res);
        }
      } else {
        util.alert(res.Message);
      }
    });
  },
  /**加载限时特价商品列表 */
  loadPanicProductList(data, callback) {
    var entity = authorize.getEntity();
    var param = {
      FKFlag: app.dns.proprietor,
      FKId: app.dns.proprietorId,
      ProprietorId: app.dns.proprietorId,
      UserId: entity.fkId,
      FKWay: app.dns.fkWay,
      PageIndex: data.PageIndex,
      PageSize: data.PageSize,
      ActivityObject: true,
      keyword: data.keywords,
      orderby: "<" + data.sortField + ">" + data.sortDirect + "</" + data.sortField + ">",
      dataType: data.dataType
    };
    util.post("market.panicbuy.list", param, function(res) {
      res = res.data;
      if (res.Success) {
        group.set_differ_time(res.Content.data, data.dataType);
        if (callback != undefined && typeof(callback) == "function") {
          callback(res);
        }
      } else {
        util.alert(res.Message);
      }

    });
  },
  /**
   * 设置时间缀
   */
  set_differ_time(list, t) {
    for (var i = 0; i < list.length; i++) {
      var ent = list[i];
      if (t == 1) {
        //正在进行
        var begin = Date.parse(new Date()); //当前时间戳
        var end = Date.parse(new Date(ent.EndTime));
        ent.differ_time = (end - begin) / 1000;
      } else {
        //即将开始
        var end = Date.parse(new Date(ent.StartTime)); //当前时间戳
        var begin = Date.parse(new Date());
        ent.differ_time = (end - begin) / 1000;
      }
    }
  },
  /**
   * 倒计时
   */
  setCountDown(that) {
    var list = that.data.goodsList || [];

    function caculate_time() {
      if (list.length > 0) {
        for (var i = 0; i < list.length; i++) {
          var ent = list[i];
          var intDiff = ent.differ_time; //获取数据中的时间戳
  
          var day = 0,
            hour = 0,
            minute = 0,
            second = 0;
          if (intDiff > 0) { //转换时间
            day = Math.floor(intDiff / (60 * 60 * 24));
            hour = Math.floor(intDiff / (60 * 60)) - (day * 24);
            minute = Math.floor(intDiff / 60) - (day * 24 * 60) - (hour * 60);
            second = Math.floor(intDiff) - (day * 24 * 60 * 60) - (hour * 60 * 60) - (minute * 60);
            if (hour <= 9) hour = '0' + hour;
            if (minute <= 9) minute = '0' + minute;
            if (second <= 9) second = '0' + second;
            ent.differ_time--;
            ent.time = {
              c1: day,
              c2: hour,
              c3: minute,
              c4: second,
              c0: true
            };
          } else {
            ent.time = {
              c0: false
            }
            clearInterval(that.data.timer);
          }
        }
        that.setData({
          goodsList: list
        });
      }
    }
    caculate_time();
    clearInterval(that.data.timer)
    that.data.timer = setInterval(caculate_time, 1000);
  },
  /**解析拼团预售规则 */
  parseRule: function (d, q) {
    q = q * d.translated;
    var rs = d.rule;
    var pt = d.priceType; //价格类型
    var t = {
      pid: d.pid,
      gid: d.gid,
      price: 0,
      integral: 0,
      advice: 0,
      has: false
    };
    if (d && rs != null && pt == '0') {
      for (var i = 0, len = rs.length; i < len; i++) {
        // if (t.has)
        //   continue;
        var r = rs[i];
        //数量为零时，取最小值
        if( q == 0 ){
          if(i==0){
            t.has = true;
            t.price = r.Price;
            t.integral = r.Integral;
          }else{
            if (t.price > r.Price) {
              t.price = r.Price;
              t.integral = r.Integral;
              t.has = true;
            }
            if (t.price == r.Price && t.integral > r.Integral) {
              t.integral = r.Integral;
              t.has = true;
            }
          }
        }else{
          if (q >= r.MinQuantity && q <= r.MaxQuantity) {
            t.has = true;
            t.price = r.Price;
            t.integral = r.Integral;
          }
        }
      }
    }
    return t;
  }
}
var promotion={
  /**加载限时特价商品列表 */
  loadList(data, callback) {
    var entity = authorize.getEntity() || authorize.getDefault();
    var param = {
      FKFlag: app.dns.proprietor,
      FKId: app.dns.proprietorId,
      ProprietorId: app.dns.proprietorId,
      Proprietor: app.dns.proprietor,
      UserId: entity.fkId,
      Token:entity.manager.Token,
      PageIndex: data.pageIndex,
      PageSize: data.pageSize,
      DataType: data.dataType
    };
    util.post("market.promotion.list", param, function (res) {
      res = res.data;
      if (res.Success) {
        var content = res.Content;
        var config = wholesaleSettings.getConfig();
        for(var i=0;i<content.data.length;i++){
          var p = content.data[i];
          if (p.DiscountMode == 1 || p.DiscountMode == 4){
            p.DiscountDesc ="满减";
          }
          else if (p.DiscountMode == 2 || p.DiscountMode == 5) {
            p.DiscountDesc = "打折";
          }
          else if (p.DiscountMode == 3 || p.DiscountMode == 6) {//优惠改满赠
            p.DiscountDesc = "满赠";
          } else if (p.DiscountMode == 7) {
            p.DiscountDesc = "满降";
          }
          var info = "", isDiscountCon=false;
          if (p.DiscountMode == 1 || p.DiscountMode == 2 || p.DiscountMode == 3) {//多品改 商品组合
            info = (p.PromotionType == 1 ? "单品" : "商品组合") +  "金额" + (p.DiscountCalcType == 1?"每":"")+"满"
          }
          else if (p.DiscountMode == 4 || p.DiscountMode == 5 || p.DiscountMode == 6 || p.DiscountMode == 7){
            info = (p.PromotionType == 1 ? "单品" : "商品组合") +  "数量" + (p.DiscountCalcType == 1 ? "每" : "") + "满"
            isDiscountCon=true;
          }
          var unit=""
          if (p.DiscountMode == 1 || p.DiscountMode == 2 || p.DiscountMode == 3){
            unit="元";
          }
          var action_temp="",isDiscount=false;
          if (p.DiscountMode == 1 || p.DiscountMode == 4){
            action_temp ="，立减{0}元"
          }
          else if(p.DiscountMode == 2 || p.DiscountMode == 5){
            action_temp = "，打{0}折";
            isDiscount=true;
          } else if (p.DiscountMode == 7) {
            action_temp = "，单价立降{0}元";
          }
          // console.log( p.PromotLadder[1],'=====1');
          if(p.PromotLadder && p.PromotLadder.length>0){
            if(p.EnableSkuMode==1){
              var pl = p.PromotLadder[0];
              // 折扣保留小数点后位数,最多2位
              let discountValue = pl.DiscountValue
              discountValue = util.precisionX(discountValue, 10)
              let fixed = getLengthAfterDot(discountValue)
              fixed = fixed > 2 ? 2 : fixed
              discountValue = discountValue.toFixed(fixed)
              // 满数量条件
              if (p.DiscountMode == 4 || p.DiscountMode == 5 || p.DiscountMode == 6 || p.DiscountMode == 7) {
                unit = pl.Unit || ''
              }
              pl.PromotionInfo= info + (isDiscountCon ? pl.MinimumValue : pl.MinimumValue.toFixed(2)) + unit+
                action_temp.format(isDiscount ? discountValue : (pl.DiscountValue));
              if (pl.Gifts && pl.Gifts != "") {
                // 送本品
                if (pl.GiftType == 1) {
                  pl.PromotionInfo += '，送本品'
                  if (pl.GiftsNum > 0) {
                    pl.PromotionInfo += pl.GiftsNum + pl.GiftsUnit || ''
                  }
                } else {
                  // 送赠品
                  if (pl.GiveMethod == 1) {
                    pl.PromotionInfo += `，任选${pl.GiveCount || ''}种赠品`
                  } else {
                    pl.PromotionInfo += '，送赠品'
                    pl.PromotionInfo += pl.GiftsNumTotal || ''
                  }
                }
              }
              if (pl.Coupons && pl.Coupons != "") {
                pl.PromotionInfo += "，送优惠劵";
              }
              if (pl.FreeFreight == 1) {
                pl.PromotionInfo += "，免邮";
              }
              if(p.PromotLadder.length>1){
                pl.PromotionInfo += "等";
              }
            }else{
              for (var j = 0; j < p.PromotLadder.length;j++){
                var pl = p.PromotLadder[j];
                // 折扣保留小数点后位数,最多2位
                let discountValue = pl.DiscountValue
                discountValue = util.precisionX(discountValue, 10)
                let fixed = getLengthAfterDot(discountValue)
                fixed = fixed > 2 ? 2 : fixed
                discountValue = discountValue.toFixed(fixed)
                // 满数量条件，并且为商品组合时
                if (p.DiscountMode == 4 || p.DiscountMode == 5 || p.DiscountMode == 6 || p.DiscountMode == 7) {
                  if (pl.PromotUnitType == 2) {
                    unit = '销售单位'
                  } else {
                    unit = '基础单位'
                  }
                }
                pl.PromotionInfo= info + (isDiscountCon ? pl.MinimumValue : pl.MinimumValue.toFixed(2)) + unit+
                  action_temp.format(isDiscount ? discountValue : (pl.DiscountValue));
                if (pl.Gifts && pl.Gifts != "") {
                  // 送本品
                  if (pl.GiftType == 1) {
                    pl.PromotionInfo += '，送本品'
                    if (pl.GiftsNum > 0) {
                      pl.PromotionInfo += pl.GiftsNum + pl.GiftsUnit || ''
                    }
                  } else {
                    // 送赠品
                    if (pl.GiveMethod == 1) {
                      pl.PromotionInfo += `，任选${pl.GiveCount || ''}种赠品`
                    } else {
                      pl.PromotionInfo += '，送赠品'
                      pl.PromotionInfo += pl.GiftsNumTotal || ''
                    }
                  }
                }
                if (pl.Coupons && pl.Coupons != "") {
                  pl.PromotionInfo += "，送优惠劵";
                }
                if (pl.FreeFreight == 1) {
                  pl.PromotionInfo += "，免邮";
                }
              }
            }
          }
        }
        if (callback != undefined && typeof (callback) == "function") {
          callback(content);
        }
      } else {
        util.alert(res.Message);
      }

    },"3.0");
  },
  getPromotionDetail(data,callback){
    var param = {
      FKFlag: app.dns.proprietor,
      FKId: app.dns.proprietorId,
      PromId:data.promId
    };
    util.post("market.promotrule.detail",param,function(res){
      res = res.data;
      if(res.Success){
        var content = res.Content;
        if (callback != undefined && typeof (callback) == "function") {
          callback(content);
        }
      }else{
        util.alert(res.Message)
      }
    },'3.0',null,false)
  }
}
/**商品活动相关 */
const activities = {
  /**加载商品活动等信息 
   * @param  商品列表对象
   * @param {Boolean} hideActivity 是否隐藏拼团、预售、特价、促销活动
   */
  loadProductActivities(goodslist, hasMaket = false, rule_id, areaId, callback, index, hideActivity) {
    var productIds = [];
    var fkIds = [];
    if (goodslist==undefined || goodslist.length == 0) return;
    for (var i = 0; i < goodslist.length; i++) {
      var good = goodslist[i];
      good.FKId = good.FKId || good.SupplierId;
      productIds.push(good.ProductId);
      fkIds.push(good.SupplierId);
    }
    var entity = authorize.getEntity()|| authorize.getDefault();
    var param = {
      Proprietor: app.dns.proprietor,
      ProprietorId: app.dns.proprietorId,
      FKFlag: app.dns.proprietor,
      FKIds: fkIds[0],
      ProductIds: productIds.join(","),
      Token: entity.manager.Token,
      AreaId: areaId
    };
    var that = this;
    util.post("market.product.extends", param, function (res) {
      var d = res.data.Content || {};
      // 隐藏拼团、预售、特价、促销活动
      if (hideActivity) {
        d.Groupbuy = {}
        d.Group = {}
        d.PanicBuy = {}
        d.Promotions = {}
      }
      var cd = {//需要处理的数据队列
        gifts: d.Gifts || {},
        coupons: d.Coupons || {},
        sales: hasMaket == false ? (d.Groupbuy || {}) : {},//预售
        groups: hasMaket == false ? (d.Group || {}) : {},//拼团
        panics: hasMaket == false ?(d.PanicBuy || {}) : {},//特价
        promotions: d.Promotions || {},
      };
      var dic = res.data.Content;
      for (var n = 0; n < goodslist.length; n++) {
        var good = goodslist[n];
        let originalProductData = deepClone(good)
        let productMarkets = activities.computeMarkets(cd, { isList: true },good.ProductId,good.AuxUnit,rule_id?rule_id:0,good.Unit, good.DefaultUnit) || [];
        good.loadcomplate = 1;
        good.DiscountId = 0;
        good.DiscountType = 0;
        good.linkParam = "ptype=0&id=" + good.ProductId + "&sid=" + good.SupplierId + "&productId=" + good.ProductId;
        good.pageType = 0;
        good.Promotions=[];
        good.Gift = [];
        good.PanicBuy = [];
        good.Label=[];
        let key = "{0}_{1}_{2}".format(good.FKId, good.ProductId, 0);
        let productMarket=productMarkets[key];
        if (productMarket==undefined) continue;
        productMarket.markets.reverse().map((item)=>{
          good = activities.signProduct(good, item);
        });
        var market = [];
        var label = [];
        let promotionsLabel = [] // 显示的促销label
        let firstLabelIndex = -1 // 如果为组合促销，那么其中最先有当前商品的index
        if (good.isGroup) {
          market.push("拼团");
          var groups=dic.Group;
          that.stockSale(good,groups,1)
        } else if (good.isPresale) {
          market.push("预售");
          var groups=dic.Groupbuy;
          that.stockSale(good,groups,2)
        } else if (good.isPanic) {
          market.push("特价");
          var groups=dic.PanicBuy;
          that.stockSale(good,groups,3)
        } else if (good.isPromotions) {
          good.Promotions.map((item, index)=>{
            // label中有单品促销时，直接取单品促销
            if (item.productIds == good.ProductId) {
              promotionsLabel = [item]
            } else {
              // 判断是否在组合促销内
              let ids = item.productIds || ''
              ids = ids.split(',')
              let i = ids.findIndex((productId) => {
                return productId == good.ProductId
              })
              if (i != -1 && firstLabelIndex == -1) {
                firstLabelIndex = index
              }
            }
            if(good.IsSingle === 1){
              label.push(good.Promotions[0].label)
              market.push(good.Promotions[0].name)
            }else{
              label.push(good.Promotions.length > 0?good.Promotions[good.Promotions.length-1].label:'')
              market.push(good.Promotions.length > 0?good.Promotions[good.Promotions.length-1].name:'')
            }
            // market.push(item.name)
            // label.push(item.label)
          });
          // 没有找到单品促销，并且有组合促销，则取组合促销的第一个
          if (promotionsLabel.length == 0) {
            if (firstLabelIndex != -1) {
              promotionsLabel.push(good.Promotions[firstLabelIndex])
            }
          }
          good.promotionsLabel = promotionsLabel
        }
        if (good.isGift && !good.isGroup && !good.isPresale) {
          market.push("赠品");
        }
        if (good.isCoupon && !good.isGroup && !good.isPresale && !good.isPanic) {
          market.push("领券");
        }
        let el = market.filter((item,index)=>market.indexOf(item)===index);
        let els = label.filter((item,index)=>label.indexOf(item)===index);
        good["market"] = el;
        good["Label"] = els;
        good.originalProductData = originalProductData
        goodslist[n] = good;
      }
      if (callback != undefined && typeof (callback) == "function") {
        callback(goodslist, index);
      }
    }, "3.0", null, false);
  },
  stockSale(good,groups,num){
    var that = this;
    for(var keys in groups){
      var prom = groups[keys];
      if(prom != '' && Array.isArray(prom)){
        prom.forEach(function(group){
          if(group.ProductId == good.ProductId){
            if(num == 3){
              if(good.IsSingle == 1){
                var panic = group.PanicGoods;
                for(var i=0;i<panic.length;i++){
                  if (good.ProductGoodsId == panic[i].GoodsId) {
                    var remainderQuantity = panic[i].Quantity - panic[i].BuyQuantity;
                    //允许0库存，显示可用活动数量；不允许0库存，显示库存、活动可以数量的小值
                    if(good.ZeroStockBuy==0){
                      remainderQuantity = remainderQuantity<good.SStock?remainderQuantity:good.SStock
                    }
                    good.Stock = remainderQuantity;
                    good.SStock = remainderQuantity;
                    good.StockText = remainderQuantity+good.Unit;
                    good.BuyLowerLimit = panic[i].MinQuantity;
                    good.BuyUpperLimit = panic[i].MaxQuantity > 0 && panic[i].MaxQuantity <= remainderQuantity ? panic[i].MaxQuantity : remainderQuantity;
                    good.SBuyLowerLimit = good.BuyLowerLimit || 0;
                    good.SBuyUpperLimit = good.BuyUpperLimit || 0;
                    break;
                  }
                }
              } else {
                good.Stock = group.Stock;
                good.SStock = group.Stock;
                good.StockText = good.SStock+good.Unit;
              }
              var t = detail.parseRule(good.UnitPrices, good.Radix, good.CartCount==0?1:good.CartCount);
              if(t.has){
                good.Price = t.MarketPrice;
                good.originalPrice = t.originalPrice;
              }else{
                good.Price = group.MarketPrice;
                good.originalPrice = group.CostPrice;
              }
            }else{
              good.BuyLowerLimit = group.BuyMinQuantity || 0;
              good.SBuyLowerLimit = group.BuyMinQuantity || 0;
              if (group.RemainQty>0) {
                good.StockText = group.RemainQty+good.Unit;
              }
              good.Price = group.MarketPrice;
            }
          }
        })
      }
    }
  },
  signProduct(good, item){
    if (item.type == 1){
      good = activities.packProductGroup(good, item);
    }
    else if (item.type == 2) {
      good = activities.packProductPresale(good,item);
    }
    else if (item.type == 3) {
      good = activities.packProductPanic(good, item);
      good.PanicBuy.push(item); 
    }
    else if (item.type == 4) {
      good.isPromotions = true;
      good.Promotions.push(item);
      good.Label.push(item.label);
    }
    else if (item.type == 5) {
      good.isGift = true;
      good.Gift.push(item);
    }
    else if (item.type == 6) {
      good.isCoupon = true;
    }
    return good
  },
  /**
   * @param {String} Unit 商品基础单位
   * @param {String} DefaultUnit 商品默认销售单位
   */
  computeMarkets(markets, args,ProductId,AuxUnit,rule_id,Unit, DefaultUnit) {
    var that = this;
    args = args || {};
    var products = []; //{key:[]}//“打折、满减、优惠 “满赠”改为用“优惠”
    var marks = ["", "拼团", "预售", "特价", "促销", "赠品", "领券"]; //下标为类型
    let isList = args.isList == true;
    let isRule = args.isRule == true;
    function madeMarket(type, list) {
      list = list || {};
      if (Object.keys(list).length < 1) {
        return products;
      }
      type = type || 0;
      for (var k in list) {
        var items = list[k] || [];
        for (var i = 0, len = items.length; i < len; i++) {
          var item = items[i];
          var md = {
            id: item.Id || 0,
            name: marks[type],
            type: type,
            marketName: type == 3 ? (item.Title || ""):(item.Name || ""),
            fkFlag: item.FKFlag || 0,
            fkId: item.FKId || 0,
            productId: item.ProductId || 0,
            goodsId: item.GoodsId || 0,
            salePrice: item.Price || 0,
            productIds: item.ProductIds || "",
            goodsIds: item.GoodsIds || "",
            quantity: item.Quantity || 0,
            marketGoods: [],
            label:'',
          };
          if (type == 5) {//赠品需要切换字段
            md.productId = item.PriProductId || "";
          }
          if (md.productIds == "")
            md.productIds = md.productId + "";
          if (md.goodsIds == "")
            md.goodsIds = md.goodsId + "";
          if (type == 4) {
            var promotLadders = null;
            var allList = [];
            for(var j=0;j<item.PromotLadder.length;j++){
              // console.log(item.PromotLadder,ProductId)
              if(item.PromotLadder.length>1){
                if(item.PromotLadder[j].ProductId == ProductId){
                  allList.push(item.PromotLadder[j]);
                }
                if(allList.length>1){
                  var min = allList[0].MinimumValue;
                  for(var g=0;g<allList.length;g++){
                    if(allList[g].MinimumValue < min){
                      promotLadders = allList[g]
                    }
                  }
                }else{
                  if(item.PromotLadder[j].ProductId == ProductId){
                    promotLadders = item.PromotLadder[j]
                  }
                }
              }else{
                promotLadders = item.PromotLadder[j]
              }
              if(!promotLadders){
                promotLadders = item.PromotLadder[j]
              }
            }
            if(promotLadders){
              promotLadders.AuxUnit = AuxUnit;
              promotLadders.ProductUnit = Unit
              md.label = that.builderPromotLadder(item.PromotionType,item.DiscountCalcType,item.DiscountMode,promotLadders,item.EnableSkuMode, Unit, DefaultUnit);
            }
            // console.log(promotLadders,'=======-promotLadders',md,rule_id);
            // md.label = that.builderPromotLadder(item.PromotionType,item.DiscountCalcType,item.DiscountMode,item.PromotLadder[0],item.EnableSkuMode);
            //商品列表显示了促销详请就不再详情促销标签
            if(rule_id > 0 && md.id == rule_id){
              continue;
            }
            if (item.DiscountMode == 1 || item.DiscountMode == 4){
              md.name = "满减";
            }   
            else if (item.DiscountMode == 2 || item.DiscountMode == 5){
              md.name = "打折";
            }else if (item.DiscountMode == 3 || item.DiscountMode == 6){
              md.name = "满赠";//优惠改满赠
            } else if (item.DiscountMode == 7) {
              md.name = "满降"; // 商品满一定数量，单价立降XX元
            }
          }
          
          if (type == 3) {
            md.marketGoods = item.PanicGoods || [];
            md.ExceedLimitOriginalPriceBuy = item.ExceedLimitOriginalPriceBuy || 0
          }

          var pros = md.productIds.split(',');
          for (var j = 0, jen = pros.length; j < jen; j++) {
            var proId = pros[j];
            var key = "{0}_{1}_{2}".format(md.fkId, proId, isList && type == 5 ? 0 : md.goodsId);
            var market = products[key] || { showStepper: true, salesPrice: -1, marketType: 0, markets: [] };
            let limited = { panic: false, presale: false, group: false, sales: false, gifts: false };
            for (let m = 0, mlen = (market.markets || []).length; m < mlen; m++) {
              const mk = market.markets[m];
              limited.group = mk.name == '拼团';
              limited.presale = mk.name == '预售';
              limited.panic = mk.name == '特价';
              limited.sales = mk.name == '优惠';
              limited.coupons = mk.name == '领券';
              limited.gifts = mk.name == "赠品";
            }
            if (type != 5) {//非赠品
              // if (limited.group == true)
              //   continue;
              // if (limited.presale == true)
              //   continue;
              // if (limited.panic == true && md.name == "优惠")
              //   continue;
              // if (limited.panic == true && md.name == "打折")
              //   continue;
              // if (limited.panic == true && md.name == "满减")
              //   continue;
              // if (limited.sales == true && md.name == "优惠")//防止重复优惠
              //   continue;
            } else {
              // if (limited.gifts == true && md.name == "赠品")
              //     continue;
            }
            if (type == 1 || type == 2 || type == 3) {
              market.salesPrice = md.salePrice;
              market.discountType = type;
              market.discountId = item.Id || 0;
            }
            if (market.showStepper == true)
              market.showStepper = (type == 1 || type == 2 ? false : true);

            market.markets.push(md);
            products[key] = market;
          }
        }
      }
      return products;
    }
    if (isRule != true) {
      madeMarket(1, markets.groups);
      madeMarket(2, markets.sales);
      madeMarket(3, markets.panics);
    }
    madeMarket(4, markets.promotions);
    madeMarket(5, markets.gifts);
    madeMarket(6, markets.coupons);

    return products;
  },
  /**
   * @param {String} Unit 商品单位
   * @param {String} DefaultUnit 默认销售单位
   */
  builderPromotLadder: function (promotionType, discountCalcType, discountMode, promotLadder, enableSkuMode, Unit, DefaultUnit) {
    // console.log(promotLadder,'======promotLadder')
    //组合满200元减5元
    var info = "";
    //组合促销
    if (promotionType == 2) {
        info += "组合";
    }
    //金额
    if (discountMode == 1 || discountMode == 2 || discountMode == 3) {
        info += (discountCalcType == 1?"每满":"满") + parseFloat(promotLadder.MinimumValue) + "元";
    }
    //数量
    else {
        // 商品数量单位，按后台返回展示
        // enableSkuMode: 是否是单独设置的商品单位
        // PromotUnitType: 满多少商品单位条件 1基础单位 2销售单位 0未选择单位（单独设置商品时不知道时基础还是销售单位）
        // GiftsUnitType: 同上，和PromotUnitType类似
        info += (discountCalcType == 1?"每满":"满") + parseFloat(promotLadder.MinimumValue);
        let unitName = ''
        if (enableSkuMode == 1) {
          // 单独设置单位的，直接使用接口返回的单位
          unitName = promotLadder.Unit || promotLadder.GiftsUnit || ''
        } else {
          if (promotLadder.PromotUnitType == 2) {
            // 销售单位
            unitName = DefaultUnit || promotLadder.AuxUnit || ''
          } else {
            // 基础单位
            unitName = Unit || promotLadder.Unit || promotLadder.GiftsUnit || ''
          }
        }
        info += unitName
    }
    //立减
    if (discountMode == 1 || discountMode == 4) {
        info += "减" + parseFloat(promotLadder.DiscountValue) + "元";
    }
    //打折
    else if (discountMode == 2 || discountMode == 5) {
        info += "打" + (util.formatFloat(promotLadder.DiscountValue * 10 ,2)) + "折";
    }
    //满赠
    else if (discountMode == 3 || discountMode == 6) { 
      if(promotLadder.Gifts && promotLadder.Gifts!=''){
        if (promotLadder.GiftType == 1) {
          info += '送本品'
          if (promotLadder.GiftsNum > 0) {
            info += promotLadder.GiftsNum
            // 按商品单独设置时，直接使用接口返回的单位
            if (enableSkuMode == 1) {
              info += promotLadder.GiftsUnit || ''
            } else {
              if (promotLadder.GiftsUnitType == 1) {
                // 基础单位
                info += promotLadder.ProductUnit || ''
              } else {
                // 销售单位
                info += promotLadder.AuxUnit || ''
              }
            }
          }
        } else {
          if (promotLadder.GiveMethod == 1) {
            info += `任选${promotLadder.GiveCount || ''}种赠品`
          } else {
            // GiftsNumTotal：赠品总数
            info += '送赠品'
            info += promotLadder.GiftsNumTotal || ''
          }
        }
      }else if(promotLadder.FreeFreight == 1){
        info += "包邮";
      }else if(promotLadder.Coupons && promotLadder.Coupons != ''){
        info += "送优惠券";
      }
    } else if (discountMode == 7) {
      info += "单价立降" + parseFloat(promotLadder.DiscountValue) + "元";
    }
    return info;
  },
  /**加载商品特价信息 */
  packProductPanic(good,e) {
    var panicGoods = e.marketGoods[0];
    // good.originalPrice = good.CostPrice;
    good.PanicGoods = e.marketGoods;
    good.SalesPrice = e.salePrice;
    good.MinPrice = e.salePrice;
    good.SaleMode = 0;
    good.SalesIntegral = 0;
    good.MinIntegral = 0;
    good.MaxIntegral = 0;
    good.DiscountId = e.id;
    good.DiscountType = 2;
    if (good.IsSingle == 1) {
      good.BuyLowerLimit = panicGoods.MinQuantity || 0;
      good.BuyUpperLimit = panicGoods.MaxQuantity || 0;
      good.SBuyLowerLimit = panicGoods.MinQuantity || 0;
      good.SBuyUpperLimit = panicGoods.MaxQuantity || 0;
    }
    good.linkParam = "ptype=3&id=" + e.productId + "&discounttype=2&discountid=" + e.id + "&productId=" + e.productId;
    good.pageType = 3;
    good.isPanic = true;
    return good
  },
  /**加载商品拼团信息 */
  packProductGroup(good,e) {
    good.SalesPrice = e.salePrice;
    good.SaleMode = 0;
    good.MinPrice = e.salePrice;
    good.SalesIntegral = 0;
    good.MinIntegral = 0;
    good.MaxIntegral = 0;
    good.linkParam = "ptype=1&id=" + e.id + "&productId=" + e.productId;
    good.pageType = 1;
    good.isGroup = true;
    return good
  },
  /**加载商品预售信息 */
  packProductPresale(good,e) {
    // console.log(e,'-------1');
    good.SalesPrice = e.salePrice;
    good.MinPrice = e.salePrice;
    good.SaleMode = 0;
    good.SalesIntegral = 0;
    good.MinIntegral = 0;
    good.MaxIntegral = 0;
    good.linkParam = "ptype=2&id=" + e.id + "&productId=" + e.productId;
    good.pageType = 2;
    good.isPresale = true;
    return good;
  },
  /**获取当前用户对此活动是否能够购买 */
  getGroupOrderCount(data, callback) {
    var param = {
      Proprietor: app.dns.proprietor,
      ProprietorId: app.dns.proprietorId,
      FKFlag: app.dns.proprietor,
      FKId: app.dns.proprietorId,
      FKWay: app.dns.FKWay,
      GroupId: data.GroupId,
      Flag: data.Flag,
      UserId: data.entity.fkId,
      UserFlag: data.entity.fkFlag
    };
    util.post("order.groupbuy.getordercount", param, function (res) {
      res = res.data;
      if (res.Success) {
        if (callback != undefined && typeof (callback) == "function") {
          callback(res.Content);
        }
      }
    }, "3.0", null, false);
  },
  /**
   * 获得营销规则接口
   */
  getPromoteRuleInfo(ruleId, callback) {
    var param = {
      Proprietor: app.dns.proprietor,
      ProprietorId: app.dns.proprietorId,
      FKFlag: app.dns.proprietor,
      FKId: app.dns.proprietorId,
      PromId: ruleId,
    };
    util.post("market.promotrule.info", param, function (res) {
      res = res.data;
      if (res.Success) {
        if (callback != undefined && typeof (callback) == "function") {
          var promotRule = res.Content;
          var ent = {};
          if (promotRule.Id > 0) {
            ent = promotRule.CuponsRule == 0 ? activities.parsePromotRule(promotRule) : activities.parseCouponRule(promotRule);
          }
          if (promotRule.MustBuyGoods) {
            ent.MustBuyGoods = promotRule.MustBuyGoods || []
          }
          callback(ent);
        }
      }
    }, "3.0", null, false);
  },
  parsePromotRule: function (rule) {
    var ent = {
      CuponsRule: 0,
      Title: "",
      Ladder: [],
      CuponsRule: rule.CuponsRule,
      StartTime: rule.StartTime,
      EndTime: rule.EndTime,
      DiscountMode: rule.DiscountMode,
      Name:rule.Name,
      EnableSkuMode:rule.EnableSkuMode,
    };
    var discountMode = rule.DiscountMode;
    switch (discountMode) {
      case 1:
        ent.Title = "立减";
        break;
      case 2:
        ent.Title = "打折";
        break;
      case 3:
        ent.Title = "满赠";
        break;
      case 4:
        ent.Title = "立减";
        break;
      case 5:
        ent.Title = "打折";
        break;
      case 6:
        ent.Title = "满赠";
        break;
      case 7:
        ent.Title = "满降";
        break;
    }
    
    var promotLadder = rule.PromotLadder;
    if (promotLadder.length > 0) {
      if (rule.DiscountCalcType == 1) {
        ent.Ladder.push(activities.parsePromotLadder(promotLadder[0], rule.DiscountCalcType, discountMode, rule.PromotionType,rule.EnableSkuMode));
      } else {
        for (var i = 0; i < promotLadder.length; i++) {
          ent.Ladder.push(activities.parsePromotLadder(promotLadder[i], rule.DiscountCalcType, discountMode, rule.PromotionType,rule.EnableSkuMode));
        }
      }
    }
    return ent;
  },
  parsePromotLadder: function (promotLadder, discountCalcType, discountMode, promotionType,enableSkuMode) {
    var config = wholesaleSettings.getConfig();
    var ladderInfo = "";
    var tinfo = "";
    if (promotLadder.Gifts && promotLadder.Gifts != "") {
      // 送本品
      if (promotLadder.GiftType) {
        tinfo += "，送本品"
        if (promotLadder.GiftsNum > 0) {
          tinfo += promotLadder.GiftsNum + promotLadder.GiftsUnit || ''
        }
      } else {
        // 送赠品
        if (promotLadder.GiveMethod == 1) {
          tinfo += `，任选${promotLadder.GiveCount || ''}种赠品`
        } else {
          // GiftsNumTotal：赠品总数
          tinfo += "，送赠品"
          tinfo += promotLadder.GiftsNumTotal || ''
        }
      }
    }
    if (promotLadder.Coupons && promotLadder.Coupons != "") {
      tinfo += "，送优惠劵";
    }
    if (promotLadder.FreeFreight == 1) {
      tinfo += "，免邮";
    }
    var conditionPre = "",
      baseUnit = "";
    if (discountMode < 4) {//多品改商品组合
      conditionPre = (promotionType == 1 ? "单品" : "商品组合") + "金额" + (discountCalcType == 1 ? "每" : "") + "满";
      baseUnit = "元";
    } else {
      conditionPre = (promotionType == 1 ? "单品" : "商品组合") + "数量" + (discountCalcType == 1 ? "每" : "") + "满";
    }
    ladderInfo = {
      ConditionPre: conditionPre,
      MinimumValue: promotLadder.MinimumValue,
      DiscountValue: (discountMode == 1 || discountMode == 4) ? promotLadder.DiscountValue:util.formatFloat(promotLadder.DiscountValue*10,config.priceDigits),
      BaseUnit: baseUnit,
      Other: (discountMode == 3 || discountMode == 6) ? tinfo.replace("，", "") : tinfo
    };
    switch (discountMode) {
      case 1:
        ladderInfo.Action = "立减";
        ladderInfo.ActionUnit = "元";
        break;
      case 2:
        ladderInfo.Action = "打";
        ladderInfo.ActionUnit = "折";
        break;
      case 3:
        break;
      case 4:
        ladderInfo.Action = "立减";
        ladderInfo.ActionUnit = "元";
        break;
      case 5:
        ladderInfo.Action = "打";
        ladderInfo.ActionUnit = "折";
        break;
      case 6:
        break;
      case 7:
        ladderInfo.Action = "单价立降";
        ladderInfo.ActionUnit = "元";
        break;
    }
    return ladderInfo;
  },
  parseCouponRule: function (rule) {
    var ent = {
      Title: "",
      Info: "",
      ActionUnit: "",
      CuponsRule: rule.CuponsRule,
      CuponsRule: rule.CuponsRule,
      StartTime: rule.StartTime,
      EndTime: rule.EndTime,
      TermDay: rule.TermDay,
      TermType: rule.TermType
    };
    var discountMode = rule.DiscountMode;
    var promotLadder = rule.PromotLadder[0];
    if (discountMode == 1 || discountMode == 4) {
      ent.Title = "¥" + util.formatFloat(promotLadder.DiscountValue, 2, true);
    } else {
      ent.Title = util.formatFloat(promotLadder.DiscountValue * 10, 2, true);
      ent.ActionUnit = "折";
    }
    ent.Info = rule.PromotionType == 1 ? "单品" : "商品组合";//多品改商品组合
    ent.Info += "满" + util.formatFloat(promotLadder.MinimumValue, 2, true) + (discountMode == 1 || discountMode == 2 ? "元" : "个") + "可使用";
    var terminalText = activities.praseTerminalName(rule.Terminal);
    if (terminalText != "") {
      ent.Info += "（" + terminalText + "）";
    }
    return ent;
  },
  praseTerminalName: function (terminal) {
    switch (terminal.toString()) {
      case '0':
        return "不限终端";
      case '1':
        return "限PC端";
      case '2':
        return "限移动端";
      default:
        return '';
    }
  }
}
class advert{
  /**
* 获得大礼包
*/
  static getAdvertScreen(data, callback) {
    var entity = authorize.getEntity() || authorize.getDefault()
    var param = {
      Proprietor: app.dns.proprietor,
      ProprietorId: app.dns.proprietorId,
      UserId: entity.fkId,
      FKId: app.dns.proprietorId,
      FKFlag: app.dns.proprietor
    };
    util.post("market.promotion.advertscreen", param, function (res) {
      res = res.data;
      if (res.Success) {
        if (callback != undefined && typeof (callback) == "function") {
          callback(res.Content);
        }
      }
    }, "3.0", null, false)
  }
  /**
   *  更新展现量\点击量
   */
  static updateScanNum(data, callback) {
    var entity = authorize.getEntity();
    var param = {
      Proprietor: app.dns.proprietor,
      ProprietorId: app.dns.proprietorId,
      Type: data.type,
      AdvertId: data.id,
      Count: data.count
    };
    util.post("market.promotion.updcount", param, function (res) {
      res = res.data;
      if (callback != undefined && typeof (callback) == "function") {
        callback(res);
      }

    }, "3.0", null, false)
  }
}

const liveService={
  getPage: function(data, callback) {
    var entity = authorize.getEntity() || authorize.getDefault()
    var param = {
      Proprietor: app.dns.proprietor,
      ProprietorId: app.dns.proprietorId,
      FKId: app.dns.proprietorId,
      FKFlag: app.dns.proprietor,
      PageIndex:data.pageIndex,
      PageSize:data.pageSize
    };
    util.post("market.live.broadcast", param, function (res) {
      res = res.data;
      console.log("live",res)
      if (res.Success) {
        if (callback != undefined && typeof (callback) == "function") {
          callback(res.Content);
        }
      }
    }, "3.0", null, false)
  },
  updateLiveStatus: function (data, callback){
    var entity = authorize.getEntity() || authorize.getDefault()
    var param = {
      id: data.id,
      status: data.status,
      Token: entity.manager.Token
    };
    util.post("market.live.push", param, function (res) {
      res = res.data;
      if (res.Success) {
        if (callback != undefined && typeof (callback) == "function") {
          callback(res.Content);
        }
      }
    }, "3.0", null, false)
  }
}

const dealing = {
  getDealing:function(data,callback){
    var entity = authorize.getEntity();
    var param = {
      Proprietor: app.dns.proprietor,
      ProprietorId: app.dns.proprietorId,
      StoreId:entity.fkId,
      OddNumber:data.OddNumber,
      BeginTime:data.BeginTime,
      EndTime:data.EndTime,
      PageIndex:data.PageIndex,
      PageSize:data.PageSize
    }
    if(data.OrderType>-1){
      param.OrderType = data.OrderType
    }
    util.post("store.dealing.list", param, function (res) {
      res = res.data;
      if (res.Success) {
        if (callback != undefined && typeof (callback) == "function") {
          callback(res.Content);
        }
      }
    }, "3.0", null, false)
  },
  /**
   * 线下往来
   */
  getOfflineData:function(time,data,callback){
    var entity = authorize.getEntity();
    var param = {
      ProprietorId: app.dns.proprietorId,
      StoreId:entity.fkId,
      TimeScope:time,
      PageIndex:data.PageIndex,
      PageSize:data.PageSize
    }
    util.post("store.underline.dealing.list", param, function (res) {
      res = res.data;
      if (res.Success) {
        if (callback != undefined && typeof (callback) == "function") {
          callback(res.Content);
        }
      } else {
        alert(res.Message)
      }
    }, "3.0", null, false)
  }
}


export {
  coupon,
  group,
  promotion,
  activities,
  advert,
  liveService,
  dealing
}